package com.apps.diet.endpoint;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.apps.diet.domain.NutriFacts;
import com.apps.diet.oxm.EditNutriFactRequest;
import com.apps.diet.oxm.EditNutriFactResponse;
import com.apps.diet.service.NutriFactsService;


/**
 * Handles nutrifact requests. 
 * <p>
 *<pre>
 * @Endpoint: similar to Spring MVC's @Controller. 
 * @PayloadRoot: similar to Spring MVC's @RequestMapping</pre>
 */
@Endpoint
public class EditNutriFactsEndpoint {

	protected static Logger logger = Logger.getLogger(EditNutriFactsEndpoint.class);

	@Resource(name="nutriFactsService")
	private NutriFactsService nutriFactsService;
	
	public static final String NAMESPACE_URI = "http://diet.apps.com/ws/schema/diet";

	public static final String REQUEST_LOCAL_NAME = "editNutriFactRequest";

	@PayloadRoot(localPart = REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI)
	@ResponsePayload
	public EditNutriFactResponse editNutriFacts( @RequestPayload EditNutriFactRequest editNutriFactRequest) {
		try {
			String editType = editNutriFactRequest.getEditType();
			NutriFacts nutriFact = editNutriFactRequest.getNutriFacts();
			if (editType.equals("ADD")){
				logger.debug("Add operation");
				nutriFactsService.createNutriFacts(nutriFact);				
			}else{
				logger.debug("Edit operation");
				nutriFactsService.updateNutriFacts(nutriFact);
			}
		}  catch (Exception e) {
			logger.error("Unable to save nutrifact");
			EditNutriFactResponse response = new EditNutriFactResponse();
			response.setCode("FAILURE");
			return response;
		}
		
		EditNutriFactResponse response = new EditNutriFactResponse();
		response.setCode("SUCCESS");

		return response;
	}
}
